package cn.qinhao.pethome.system.service.impl;

import cn.qinhao.pethome.basic.base.query.BaseQuery;
import cn.qinhao.pethome.basic.base.service.impl.BaseServiceImpl;
import cn.qinhao.pethome.basic.until.PageList;
import cn.qinhao.pethome.system.domain.Menu;
import cn.qinhao.pethome.system.mapper.MenuMapper;
import cn.qinhao.pethome.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qinhao
 * @since 2023-03-04
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public PageList<Menu> pageQuery(BaseQuery query) {
        Long total = menuMapper.queryCount(query);
        List<Menu> datas = menuMapper.queryData(query);
        for (Menu menu : datas) {
            if(menu.getParentId()!=null){
                Menu menu1 = menuMapper.selectOne(menu.getParentId());
                System.out.println(menu1.toString());
                menu.setParent(menu1);//设置上级部门
            }
        }
        return new PageList<>(total,datas);
    }

    //无限级数
    @Override
    public List<Menu> selectAll() {
        List<Menu> menus = menuMapper.selectAll();
    //查询顶级元素（多个）返回它就可以,用list集合来装父级元素
        ArrayList<Menu> roots = new ArrayList<>();
        for (Menu item : menus) {
            if(item.getParentId()==null){//为空说明没有父对象，就添加自己
                roots.add(item);
            }else{//不为空，说明有父对象，再遍历一遍列表，查找父亲，找到就添加到父亲装儿子得容器中
                for (Menu father : menus) {
                    if(item.getParentId()==father.getId()){
                        father.getChildren().add(item);
                    }
                }
            }
        }
        return roots;
    }
}
